package com.linkwedo.saas.util;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**

 * @author Administrator
 *
 */
public class DateUtil {


 private static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss";//Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]


 private DateUtil() {
 }

	/**
	 * 默认的日期格式
	 */
	public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";

	/**
	 * 按自定义日期格式格式化日期
	 * 
	 * @param target
	 * @param format
	 * @return 格式化后的日期字符串，如果传入的日期对象为NULL，返回空字符串
	 */
	public static String formatDate(Date target, String format)
	{
		if (target == null)
		{
			return "";
		}
		return new SimpleDateFormat(format).format(target);
	}

	/**
	 * 按默认日期格式 格式化日期
	 * 
	 * @param target
	 * @return 格式化后的日期字符串，如果传入的日期对象为NULL，返回空字符串
	 */
	public static String formatDate(Date target)
	{
		return formatDate(target, DEFAULT_DATE_FORMAT);
	}

	

	/**
	 * 将字符串格式化为日期对象
	 * @param dateStr
	 * @param format
	 * @return
	 */
	public static Timestamp formatToTimestamp(String dateStr, String format)
	{
		try
		{
			SimpleDateFormat sorceFmt = new SimpleDateFormat(format);
			return new Timestamp(sorceFmt.parse(dateStr).getTime()); // 一天的时间24*3600*1000
		}
		catch (ParseException e)
		{
			
			return null;
		}
	}

	/**
	 * 将Timestamp对象格式化
	 * @param time
	 * @param format
	 * @return  格式化后的日期字符串，如果传入的Timestamp对象为NULL，返回空字符串
	 */
	public static String formatTimestamp(Timestamp time, String format)
	{
		if (time == null)
		{
			return "";
		}
		return new SimpleDateFormat(format).format(time);
	}


 public static Date str2Date(String str, String format){
  if (null == str || "".equals(str)) {
   return null;
  }
   if (null == format || "".equals(format)) {
   format = DEFAULT_FORMAT;
  }
  SimpleDateFormat sdf = new SimpleDateFormat(format);
  Date date = null;
   try {
    date = sdf.parse(str);
    return date;
   } catch (ParseException e) {
    e.printStackTrace();
   }
  return null;
 }


 public static String date2Str(Date date, String format) {
  if (null == date) {
   return null;
  }
  SimpleDateFormat sdf = new SimpleDateFormat(format);
  return sdf.format(date);
 }

 
 public static String timestamp2Str(Timestamp time) {
  Date date = null;
  if(null != time){
   date = new Date(time.getTime());
  }
  return date2Str(date, DEFAULT_FORMAT);
 }

 
 public static Timestamp str2Timestamp(String str) {
  Date date = str2Date(str, DEFAULT_FORMAT);
  return new Timestamp(date.getTime());
 }
 
 public static void main(String[] args) throws Exception {
  String tm = "2011-01-01 10:00:00.123";
  Timestamp tstamp = str2Timestamp(tm);
  System.out.println(tstamp);
  System.out.println(timestamp2Str(null));
 }
}

